﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MLY.LTR
{
    public partial class ExceptionsProcessReport : System.Web.UI.Page
    {
        string CustomerId = "25";
        string ContractorId = "46";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (SessParam.OrganizationId != 25 && SessParam.OrganizationId != 46)
                Response.Redirect("~/LTR/default.aspx");
            
            // on page load - constructing all the queries for initial reports
            if (!IsPostBack)
            {
                ConstructReport1(RetutnDateXWorkDaysAgo("3"));
                ConstructReport2(RetutnDateXWorkDaysAgo("10"));
                ConstructReport3(RetutnDateXWorkDaysAgo("5"));
                ConstructReport4(RetutnDateXWorkDaysAgo("3"));
                ConstructdebateReport();
            }
        }
        #region Global functions

        private int TranslateWorkDaysToNormalDays(int Days)
        {
            int NormalDays = 0;
            DateTime Now = DateTime.Now;
            int WeekDay = (int)Now.DayOfWeek;
            if (WeekDay == 6)
            {
                Now = Now.AddDays(-1);
                WeekDay = 5;
            }
            if (WeekDay == 7)
            {
                Now = Now.AddDays(-2);
                WeekDay = 5;
            }

            while (Days > 5)
            {
                Days -= 5;
                NormalDays += 7;
            }
            NormalDays += Days;
            if (Days > WeekDay)
                NormalDays += 2;

            return NormalDays;
        }
        private int TranslateNormalDaysToWorkDays(int days)
        {
            int WorkDays = 0;
            DateTime Now = DateTime.Now;
            int WeekDay = (int)Now.DayOfWeek;
            if (WeekDay == 6)
            {
                WeekDay = 1;
                Now.AddDays(2);
                days -= 2;
            }
            if (WeekDay == 7)
            {
                WeekDay = 1;
                Now.AddDays(1);
                days -= 1;
            }

            while (days >= 7)
            {
                WorkDays += 5;
                days -= 7;
            }
            WorkDays += days;

            return WorkDays;
        }
        private string RetutnDateXWorkDaysAgo(string Days)
        {
            // calcualtares the date that was X work days ago (holidays not implemented)
            string ReturnValue;
            int TotalDaysCount = 0;
            int DaysLeftToCount;
            DateTime Date = DateTime.Now;

            try
            {
                DaysLeftToCount = int.Parse(Days);
                TotalDaysCount = TranslateWorkDaysToNormalDays(DaysLeftToCount);
                Date = Date.AddDays(-TotalDaysCount);
                ReturnValue = ReturnSQLFormattedString(Date);
            }
            catch
            {
                ReturnValue = "unknown ";
            }

            return ReturnValue;
        }

        private string ReturnSQLFormattedString(DateTime Date)
        {
            return (Date.Year.ToString() + "-" + Date.Month.ToString() + "-" + Date.Day.ToString() + " 00:00:00");
        }

        protected string CalculateTimeSince(object StartDate1, object StartDate2, object StartDate3)
        {
            DateTime date1, date2, date3;
            bool d1, d2, d3;
            d1 = DateTime.TryParse(StartDate1.ToString(), out date1);
            d2 = DateTime.TryParse(StartDate2.ToString(), out date2);
            d3 = DateTime.TryParse(StartDate3.ToString(), out date3);

            if (d1 && d2 && d3)
            {
                if ((date1 >= date2) && (date1 >= date3))
                    return CalculateTimeSince(date1);
                if ((date2 >= date1) && (date2 >= date3))
                    return CalculateTimeSince(date2);                
                return CalculateTimeSince(date3);
            }
            if (d1 && d2)
            {
                if (date1 >= date2)
                    return CalculateTimeSince(date1);
                return CalculateTimeSince(date2);
            }
            if (d1 && d3)
            {
                if (date1 >= date3)
                    return CalculateTimeSince(date1);
                return CalculateTimeSince(date3);
            }
            if (d2 && d3)
            {
                if (date2 >= date3)
                    return CalculateTimeSince(date2);
                return CalculateTimeSince(date3);
            }
            if (d1)
                return CalculateTimeSince(date1);
            if (d2)
                return CalculateTimeSince(date2);
            return CalculateTimeSince(date3);           
        }

        protected string CalculateTimeSince(object StartDate)
        {
            string ReturnValue;

            try
            {
                DateTime Now = DateTime.Now;
                DateTime SDate = DateTime.Parse(StartDate.ToString());
                TimeSpan Span = Now - SDate;
                ReturnValue = TranslateNormalDaysToWorkDays(Span.Days).ToString() + " days";
            }
            catch
            {
                ReturnValue = "unknown";
            }
            return ReturnValue;

        }

        protected string CalculateOverdueTime(object StartDate1, object StartDate2, object StartDate3, string ReportId)
        {
            DateTime date1, date2, date3;
            bool d1, d2, d3;
            d1 = DateTime.TryParse(StartDate1.ToString(), out date1);
            d2 = DateTime.TryParse(StartDate2.ToString(), out date2);
            d3 = DateTime.TryParse(StartDate3.ToString(), out date3);

            if (d1 && d2 && d3)
            {
                if ((date1 >= date2) && (date1 >= date3))
                    return CalculateOverdueTime(date1, ReportId);
                if ((date2 >= date1) && (date2 >= date3))
                    return CalculateOverdueTime(date2, ReportId);
                return CalculateOverdueTime(date3, ReportId);
            }
            if (d1 && d2)
            { 
                if (date1 >= date2)
                    return CalculateOverdueTime(date1, ReportId);
                return CalculateOverdueTime(date2, ReportId);
            }
            if (d1 && d3)
            {
                if (date1 >= date3)
                    return CalculateOverdueTime(date1, ReportId);
                return CalculateOverdueTime(date3, ReportId);
            }
            if (d2 && d3)
            {
                if (date2 >= date3)
                    return CalculateOverdueTime(date2, ReportId);
                return CalculateOverdueTime(date3, ReportId);
            }
            if (d1)
                return CalculateOverdueTime(date1, ReportId);
            if (d2)
                return CalculateOverdueTime(date2, ReportId);
            return CalculateOverdueTime(date3, ReportId);            
        }

        protected string CalculateOverdueTime(object StartDate, string ReportId)
        {
            string ReturnValue;
            int Report;
            int WorkDaysToAdd = 0;
            DateTime Now = DateTime.Now;
            int TimeSince;
            try
            {
                DateTime SDate = DateTime.Parse(StartDate.ToString());
                TimeSpan Span = Now - SDate;
                TimeSince = TranslateNormalDaysToWorkDays(Span.Days);
                Report = int.Parse(ReportId);
                switch (Report)
                {
                    case 1:
                        WorkDaysToAdd = int.Parse(Report1paramDDL.SelectedValue);
                        break;
                    case 2:
                        WorkDaysToAdd = int.Parse(Report2paramDDL.SelectedValue);
                        break;
                    case 3:
                        WorkDaysToAdd = int.Parse(Report3paramDDL.SelectedValue);
                        break;
                    case 4:
                        WorkDaysToAdd = int.Parse(Report4paramDDL.SelectedValue);
                        break;
                }
                ReturnValue = (TimeSince - WorkDaysToAdd).ToString() + " days";
            }
            catch
            {
                ReturnValue = "unknown";
            }

            return ReturnValue;
        }

        protected string FormatDate(object Date)
        {
            string RetValue;

            try
            {
                RetValue = string.Format("{0:d}", DateTime.Parse(Date.ToString()));
            }
            catch
            {
                RetValue = ("");
            }
            return RetValue;


        }
        #endregion Global functions

        protected void UpdateReport1(object Sender, EventArgs e)
        {
            string days = Report1paramDDL.SelectedValue;
            ConstructReport1(RetutnDateXWorkDaysAgo(days));
        }

        protected void UpdateReport2(object Sender, EventArgs e)
        {
            string days = Report2paramDDL.SelectedValue;
            ConstructReport2(RetutnDateXWorkDaysAgo(days));
        }
        protected void UpdateReport3(object Sender, EventArgs e)
        {
            string days = Report3paramDDL.SelectedValue;
            ConstructReport3(RetutnDateXWorkDaysAgo(days));
        }

        protected void UpdateReport4(object Sender, EventArgs e)
        {
            string days = Report4paramDDL.SelectedValue;
            ConstructReport4(RetutnDateXWorkDaysAgo(days));
        }

        #region ConstructReports

        private void ConstructReport1(string StartDate)
        {
            string yesno = (Report1YNDDL.SelectedValue == "1") ?
                "AND CustomerCatalougeCode NOT LIKE '%NO%'" : "";

            string query = "SELECT CustomerWorkOrderNumber, ContractorWorkOrderNumber, " +
                           "SendDate, RequestedDelivaryDate, PlannedDelivaryDate, " +
                           "ActualDelivaryDate, OrderNumber, TextFieldA = CASE WHEN LEN(TextFieldA) > 0 THEN TextFieldA ELSE ContractorCatalogueCode END, " +
                           "TextFieldB, TextFieldC, DateFieldA, DateFieldB, CustomerCatalougeCode " +
                           "FROM TableWorkOrder " +
                           "WHERE CustomerId = " + CustomerId + " " +
                           "AND ContractorId = " + ContractorId + " " +
                           "AND CustomerCatalougeCode NOT LIKE '%Replace%'" + " " +
                           yesno + " " +
                           "AND PlannedDelivaryDate < '" + StartDate + "' " +
                           "AND (DateFieldB IS NULL OR DateFieldB = '') " +
                           "AND (SendDate IS NULL OR SendDate = '') " +
                           "AND (ActualDelivaryDate IS NULL OR ActualDelivaryDate = '') " +
                           "AND [dbo].TPT_isRM(TextFieldA, ContractorCatalogueCode) = 1 " +
                           "AND debate = 0 " +
                           "ORDER BY PlannedDelivaryDate ASC";
            Report1DataSource.SelectCommand = query;
            Report1DataSource.DataBind();
            Report1GridView.DataBind();

        }
        private void ConstructReport2(string StartDate)
        {
            string yesno = (Report2YNDDL.SelectedValue == "1") ?
                "AND CustomerCatalougeCode NOT LIKE '%NO%'" : ""; 
            
            string query = "SELECT CustomerWorkOrderNumber, ContractorWorkOrderNumber, SendDate, RequestedDelivaryDate, PlannedDelivaryDate, " +
                           "ActualDelivaryDate, OrderNumber, TextFieldA = CASE WHEN LEN(TextFieldA) > 0 THEN TextFieldA ELSE ContractorCatalogueCode END, " +
                           "TextFieldB, TextFieldC, DateFieldA, DateFieldB, CustomerCatalougeCode " +
                           "FROM TableWorkOrder " +
                           "WHERE CustomerId = " + CustomerId + " " +
                           "AND ContractorId = " + ContractorId + " " +
                           "AND CustomerCatalougeCode NOT LIKE '%Replace%'" + " " +
                           yesno + " " +
                           "AND SendDate < '" + StartDate + "' " +
                           "AND (DateFieldB IS NULL OR DateFieldB = '') " +
                           "AND (PlannedDelivaryDate IS NULL OR PlannedDelivaryDate = '') " +
                           "AND (ActualDelivaryDate IS NULL OR ActualDelivaryDate = '') " +
                           "AND [dbo].TPT_isRM(TextFieldA, ContractorCatalogueCode) = 1 " +
                           "AND debate = 0 " +
                           "ORDER BY SendDate ASC";
            Report2DataSource.SelectCommand = query;
            Report2DataSource.DataBind();
            Report2GridView.DataBind();
        }

        private void ConstructReport3(string StartDate)
        {
            string yesno = (Report3YNDDL.SelectedValue == "1") ?
                "AND CustomerCatalougeCode NOT LIKE '%NO%'" : "";
            
            string query = "SELECT CustomerWorkOrderNumber, ContractorWorkOrderNumber," +
                           "SendDate, RequestedDelivaryDate, PlannedDelivaryDate, " +
                           "ActualDelivaryDate, OrderNumber, TextFieldA = CASE WHEN LEN(TextFieldA) > 0 THEN TextFieldA ELSE ContractorCatalogueCode END, " +
                           "TextFieldB, TextFieldC, DateFieldA, DateFieldB, CustomerCatalougeCode " +
                           "FROM TableWorkOrder " +
                           "WHERE CustomerId = " + CustomerId + " " +
                           "AND ContractorId = " + ContractorId + " " +
                           "AND CustomerCatalougeCode NOT LIKE '%Replace%'" + " " +
                           yesno + " " +  
                           "AND PlannedDelivaryDate < '" + StartDate + "' " +
                           //"AND ((SendDate < '" + StartDate + "' " +
                           //"AND DateFieldB IS NULL) OR (DateFieldB < '" + StartDate + "' AND SendDate IS NULL))" +     
                           "AND SendDate < '" + StartDate + "' " +
                           "AND DateFieldB IS NULL " +
                           "AND (ActualDelivaryDate IS NULL OR ActualDelivaryDate = '') " +
                           "AND [dbo].TPT_isRM(TextFieldA, ContractorCatalogueCode) = 1 " +
                           "AND debate = 0 " +
                           "ORDER BY PlannedDelivaryDate ASC";
            Report3DataSource.SelectCommand = query;
            Report3DataSource.DataBind();
            Report3GridView.DataBind();
        }


        private void ConstructReport4(string StartDate)
        {
            string yesno = (Report4YNDDL.SelectedValue == "1") ?
                "AND CustomerCatalougeCode NOT LIKE '%NO%'" : "";

            string query = "SELECT CustomerWorkOrderNumber, ContractorWorkOrderNumber, " +
                           "SendDate, RequestedDelivaryDate, PlannedDelivaryDate, " +
                           "ActualDelivaryDate, OrderNumber, TextFieldA = CASE WHEN LEN(TextFieldA) > 0 THEN TextFieldA ELSE ContractorCatalogueCode END, " +
                           "TextFieldB, TextFieldC, DateFieldA, DateFieldB, CustomerCatalougeCode " +
                           "FROM TableWorkOrder " +
                           "WHERE CustomerId = " + CustomerId + " " +
                           "AND ContractorId = " + ContractorId + " " +
                           "AND CustomerCatalougeCode NOT LIKE '%Replace%'" + " " +
                           yesno + " " +
                           "AND DateFieldB < '" + StartDate + "' " +
                           "AND (ActualDelivaryDate IS NULL OR ActualDelivaryDate = '') " +
                           "AND [dbo].TPT_isRM(TextFieldA, ContractorCatalogueCode) = 1 " +
                           "AND debate = 0 " +
                           "ORDER BY DateFieldB ASC";
            Report4DataSource.SelectCommand = query;
            Report4DataSource.DataBind();
            Report4GridView.DataBind();
        }

        private void ConstructdebateReport()
        {
            string query = "SELECT CustomerWorkOrderNumber, ContractorWorkOrderNumber, " +
                         "SendDate, RequestedDelivaryDate, PlannedDelivaryDate, " +
                         "ActualDelivaryDate, OrderNumber, TextFieldA = CASE WHEN LEN(TextFieldA) > 0 THEN TextFieldA ELSE ContractorCatalogueCode END, " +
                         "TextFieldB, TextFieldC, DateFieldA, DateFieldB, CustomerCatalougeCode " +
                         "FROM TableWorkOrder " +
                         "WHERE CustomerId = " + CustomerId + " " +
                         "AND ContractorId = " + ContractorId + " " +
                         "AND debate = 1 " +
                         "ORDER BY DateFieldB ASC";
            DebateReportDataSource.SelectCommand = query;
            DebateReportDataSource.DataBind();
            DebateGridview.DataBind();
        }

        protected void ExportToExcel(object Sender, EventArgs e)
        {
            if (((ImageButton)Sender).ID == "ExportToExcel1")
                MLY.Bll.ExcelExport.PrepareCsvFileFromGridview(Report1GridView, "Before_0_order");

            if (((ImageButton)Sender).ID == "ExportToExcel2")
                MLY.Bll.ExcelExport.PrepareCsvFileFromGridview(Report2GridView, "Wait_for_quote");
            
            if (((ImageButton)Sender).ID == "ExportToExcel3")
                MLY.Bll.ExcelExport.PrepareCsvFileFromGridview(Report3GridView, "Wait_for_cust_Approval");
            
            if (((ImageButton)Sender).ID == "ExportToExcel4")
                MLY.Bll.ExcelExport.PrepareCsvFileFromGridview(Report4GridView, "Wait_for_order");

            if (((ImageButton)Sender).ID == "ExportToExcelDebate")
                MLY.Bll.ExcelExport.PrepareCsvFileFromGridview(Report4GridView, "Debate");
        }
        #endregion ConstructReports
    }
}
